import wx
from twisted.internet import wxreactor
wxreactor.install()
import cardhand
import carddeck
import carddealer
import cPickle
import message

# import twisted reactor *only after* installing wxreactor
from twisted.internet import reactor, protocol
from twisted.protocols import basic

class ChatFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, parent=None, title="netjack")
        self.protocol = None  # twisted Protocol
        self.names = None

        sizer = wx.BoxSizer(wx.VERTICAL)
        innerSizer = wx.BoxSizer(wx.HORIZONTAL)
        
        self.text = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_READONLY)
        self.ctrl = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER, size=(300, 25))
        self.bDeal = wx.Button(self,-1,"Deal")
        self.bHit = wx.Button(self,-1,"Hit")
        self.bStand = wx.Button(self,-1,"Stand")

        sizer.Add(self.text, 5, wx.EXPAND)
        sizer.Add(self.ctrl, 0, wx.EXPAND)
        innerSizer.Add(self.bDeal,5, wx.EXPAND, 10)
        innerSizer.Add(self.bHit,5, wx.EXPAND, 10)
        innerSizer.Add(self.bStand,5, wx.EXPAND, 10)
        sizer.Add(innerSizer,0,wx.EXPAND)
        
        self.SetSizer(sizer)
        
        self.ctrl.Bind(wx.EVT_TEXT_ENTER, self.send)
        self.bDeal.Bind(wx.EVT_BUTTON, self.deal)
        self.bHit.Bind(wx.EVT_BUTTON, self.hit)
        self.bStand.Bind(wx.EVT_BUTTON, self.stand)
        
        self.ctrl.SetFocus()

    def send(self, evt):
        self.protocol.sendLine(str(self.ctrl.GetValue()))
        self.ctrl.SetValue("")
    
    def deal(self, evt):
        self.protocol.sendLine(cPickle.dumps(message.ClientsMessage('deal')))
        
    def hit(self, evt):
        self.protocol.sendLine(cPickle.dumps(message.ClientsMessage('hit')))
        
    def stand(self, evt):
        self.protocol.sendLine(cPickle.dumps(message.ClientsMessage('stand')))
        
class DataForwardingProtocol(basic.LineReceiver):
    def __init__(self):
        self.output = None

    def dataReceived(self, data):
        gui = self.factory.gui
        
        try:
            temp = ""
            undata = cPickle.loads(data)
            if isinstance(undata, list):
                print type(undata[0])
                if isinstance(undata[0],cardhand.Hand):
                    for hand in undata:
                        #temp += name + ":\n" + hand.__str__()
			temp += hand.__str__()
                    undata = temp
                elif isinstance(undata[0],str):
                    gui.names = undata
            else:
                undata = undata.__str__()
                print type(undata)
            # print "loads: " + undata
            
        except (cPickle.UnpicklingError,EOFError) as e:
            undata = data
            print type(e)
            print "string:\n" + "---Begin Block---\n" + undata + "\n---End Block---"
        
        gui.protocol = self
        if gui:
            val = gui.text.GetValue()
            gui.text.SetValue(val + undata)
            gui.text.SetInsertionPointEnd()

    def connectionMade(self):
        self.output = self.factory.gui.text  # redirect Twisted's output


class ChatFactory(protocol.ClientFactory):
    def __init__(self, gui):
        self.gui = gui
        self.protocol = DataForwardingProtocol

    def clientConnectionLost(self, transport, reason):
        reactor.stop()

    def clientConnectionFailed(self, transport, reason):
        reactor.stop()


if __name__ == '__main__':
    app = wx.App(False)
    frame = ChatFrame()
    frame.Show()
    reactor.registerWxApp(app)
    reactor.connectTCP("localhost", 5001, ChatFactory(frame))
    reactor.run()
